//app.js
const {
  checkLogin,
  filterObj
} = require('./utils/util')
var QQMapWX = require('./utils/qqmap-wx-jssdk.js');
var qqmapsdk;
const {
  getCitiesList,
  queryRank,
  getDictData,
  subjectList,
  messageNum
} = require('./api/api')
const {
  voluntaryConfigCity
} = require('./api/ai')
var timer = null
const {
  decodeUserInfo,
  ruleList,
  spec_and_price,
  sysConfig,
  decodeUserTotal
} = require('./api/login');
const whiteList = ['pages/index/index', 'pages/my/index', 'pages/guide/index', 'pages/test/index/index']

App({
  onLaunch: function (options) {
    if (options.query.scene) {
      const {
        scene
      } = options.query
      wx.setStorageSync('promoteUser', scene)
    }
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: 'dedao-6gwra97saa7c87a2',
        traceUser: true,
      })
    }
    this.globalData.loader = true
    let that = this
    setInterval(function () {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      if (whiteList.indexOf(currentPage.route) > -1) {
        checkLogin().then(()=>{
          that.getMessageNum()
        })
      }
    }, 10000)
    checkLogin().then(()=>{
      this.getMessageNum()
    })
    this.getSystemInfo()
    this.checkStatus(options.path)
    this.autoUpdate()
    this.getCityList()
    this.getSubjectList()

    var arr = ['edu_type', 'school_type', 'school_label']
    arr.map((item) => {
      this.getDictData(item)
    })

    const filterList = [
      'schoolFilters',
      'schoolDetailFilters',
      'majorDetailsFilters',
      'majorFilters',
      'schoolRankFilters',
      'topicFilters',
      'historyFilters',
      'optionalChooseFilters',
      'batchFilters', 'compareFilters', 'compareCheckedFilters', 'compareDetailFilters', 'optionalFilters', 'selectedIds', 'optionalSchoolFilters', 'planFilters', 'volunteerFilters', 'intelligenceFilters'
    ]
    filterList.map((item) => {
      wx.removeStorageSync(item)
    })
  },
  //  获取我的消息未读数量
  getMessageNum() {
    return new Promise(async function (resolve, reject) {
      let token = wx.getStorageSync('token');
      if (token) {
        const { result } = await messageNum();
        getApp().globalData.allCount = result.allCount
        resolve(result.allCount)
      } else {
        resolve(0)
      }
    })
  },
  watch(param) {
    const that = this
    const obj = this.globalData
    for (let key in param) {
      if (!this.watchMethods[key]) {
        this.watchMethods[key] = []
      }
      const method = param[key]
      this.watchMethods[key].push(method)
      Object.defineProperty(obj, key, {
        set(val) {
          const methods = that.watchMethods[key]
          methods.map(item => item(val))
        }
      })
    }
  },
  watchMethods: {},
  getDictData(key) {
    return new Promise(async function (resolve, reject) {
      const {
        result
      } = await getDictData(key)
      const list = result.map((item) => {
        return {
          id: item.value,
          title: item.title,
          desc: item.desc
        }
      })
      if (key == 'school_label') {
        var obj = {}
        list.map((item) => {
          obj[item.id] = item.desc
        })
        wx.setStorageSync('school_label_obj', obj)
      }
      wx.setStorageSync(key, list)
      resolve(list)
    })
  },
  getCityList() {
    const params = {
      level: 'L1'
    }
    return new Promise(async function (resolve, reject) {
      if (wx.getStorageSync('cityList')) {
        resolve(wx.getStorageSync('cityList'))
      } else {
        const {
          result
        } = await getCitiesList(params);
        const cityList = result.map((item) => {
          return {
            id: item.code,
            checked: false,
            title: item.name.length > 4 ? item.name.substring(0, 2) : item.name
          }
        })
        wx.setStorageSync('cityList', cityList)
        resolve(cityList)
      }
    })

  },
  getSubjectList() {
    return new Promise(async function (resolve, reject) {
      const {
        result
      } = await subjectList();
      wx.setStorageSync('subjectList', result)
      resolve(result)
    })
  },
  async getRank(score, provinceId, year, mainSubject, chooseList) {
    return new Promise(async function (resolve, reject) {
      var category = ''
      if (chooseList) {
        const mainSubjectList = chooseList.filter((item) => {
          return item.subjectsId == mainSubject
        })
        category = mainSubjectList.length > 0 ? mainSubjectList[0].subjectsName : ''
      } else {
        category = mainSubject
      }
      console.log(category)
      if (score == '') return
      var params = {
        score,
        provinceId,
        year,
        category
      }
      params = filterObj(params)
      // console.log(params)
      const {
        result
      } = await queryRank(params)
      resolve(result.total)
    })

  },
  getLocation() {

    let self = this;
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'ZKIBZ-5F43X-ZD74H-ZMS3D-HQXW7-QQBDF'
    });
    wx.showLoading({
      title: '加载中'
    });
    this.testLocation()
  },
  // 微信客服
  getCustomerService() {
    wx.openCustomerServiceChat({
      extInfo: {
        url: 'https://work.weixin.qq.com/kfid/kfcfae9cf6486f605e9' //这个就是客服链接
      },
      corpId: 'wwf72802c377026599', //企业ID
      success(res) {
        console.log("成功")
      },
      fail(err) {
        console.log("失败", err)
      }
    })
  },
  fetchUserInfo() {
    return new Promise(async function (resolve, reject) {
      const {
        result
      } = await decodeUserInfo()
      var userInfo = result
      const vips = result.vips
      var vipType = ''
      if (vips.indexOf('svip') > -1) {
        vipType = 'svip'
      } else if (vips.indexOf('vip') > -1) {
        vipType = 'vip'
      } else {
        vipType = ''
      }
      userInfo.vipType = vipType
      wx.setStorageSync('userInfo', userInfo)
      resolve(userInfo)
    })
  },
  fetchUserTotal() {
    return new Promise(async function name(resolve, reject) {
      const {
        result
      } = await decodeUserTotal()
      resolve(result)
    })
  },
  copy: function (text) {
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '已复制',
              icon: 'none'
            })
          }
        })
      }
    })
  },
  call(phoneNumber) {
    if (phoneNumber.length > 1) {
      wx.showActionSheet({
        itemList: phoneNumber,
        success(res) {
          phoneNumber.forEach((item, index) => {
            if (res.tapIndex == index) {
              wx.makePhoneCall({
                phoneNumber: item,
                success: function () {
                  // console.log('拨打电话成功' + item)
                },
                fail: function () {
                  // console.log('拨打电话失败')
                },
              })
            }
          })
        },
        fail(res) {
          // console.log("拨打电话失败")
        },
      })
    } else {
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        success: (res) => {},
        fail: (res) => {},
      })
    }
  },
  getQueryVariable: function (url, scence, variable, variable1) {
    var value = {}
    var vars = url.split("?");
    var pair = vars[1].split("&");
    for (var i = 0; i < pair.length; i++) {
      var param = pair[i].split('=')
      if (param[0] == scence) {
        value[scence] = param[1]
      }
      if (param[0] == variable) {
        value[variable] = param[1]
      }
      if (param[0] == variable1) {
        value[variable1] = param[1]
      }
    }
    return value;
  },
  checkStatus(path) {
    if (whiteList.indexOf(path) < 0) {
      checkLogin().then((res) => {
        this.fetchUserInfo()
      }).catch((e) => {
        wx.removeStorageSync('token')
        wx.switchTab({
          url: '/pages/index/index',
        })
      })
    }

  },
  previewImg(src, list) {
    getApp().globalData.preview = false;
    //图片预览
    wx.previewImage({
      current: src,
      urls: list
    });
  },
  getSystemInfo: function () {
    let t = this;
    let menuButtonObject = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res)
        let statusBarHeight = res.statusBarHeight;
        let navTop = menuButtonObject.top;
        let menuHeight = menuButtonObject.height
        let navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
        t.globalData.navHeight = navHeight,
          t.globalData.menuHeight = menuHeight,
          t.globalData.navTop = navTop,
          t.globalData.systemInfo = res;
        // console.log(res)
        const {
          screenHeight,
          safeArea
        } = res
        const {
          bottom
        } = safeArea
        const bottomLift = screenHeight - bottom
        const windowHeight = res.windowHeight
        t.globalData.windowHeight = windowHeight
        t.globalData.bottomLift = bottomLift
        t.globalData.mainHeight = screenHeight - t.globalData.navHeight - 10;
        const tabbarHeight = bottomLift + 128
        t.globalData.tabbarHeight = tabbarHeight
        if (wx.getStorageSync('tabbarHeight') && wx.getStorageSync('tabbarHeight') != '') {
          return
        }
        wx.setStorageSync('tabbarHeight', t.globalData.tabbarHeight)
      }
    });
  },
  editTabbar: function () {
    const type = this.globalData.type
    let tabbar = this.globalData.tabbar
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },
  async getVoluntaryConfigCity(provinceId) {
    const code = wx.getStorageSync('userCitys').code
    const params = {
      provinceId: code,
    }
    if (provinceId != undefined) {
      params.provinceId = provinceId
    }
    const {
      result
    } = await voluntaryConfigCity(params)
    if (result.length > 0) {
      var que = result.filter((item) => {
        return item.localBatchName == '专科批' || item.localBatchName == '普通类一段'
      })[0]
      var que = result[0]
      var str = que.province + que.localBatchName + '的投档录取模式为院校专业组平行志愿,' + que.description
      wx.setStorageSync('provinceDesc', str)
    }

  },
  autoUpdate: function () {
    const self = this
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        console.log("是否更新版本:", res.hasUpdate)
      })
      updateManager.onUpdateReady(function () {
        wx.showModal({
          content: '发现新版本，请重启当前小程序~',
          confirmColor: '#2f8dd6',
          confirmText: '确定重启',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })
      updateManager.onUpdateFailed(function () {
        wx.showToast({
          title: '更新失败',
          icon: "loading"
        })
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  globalData: {
    bottomLift: 0,
    navHeight: 0,
    navTop: 0,
    menuHeight: 0,
    allCount: 0,
    isLogin: false,
    slogin: 0,
    windowHeight: 0,
    mainHeight: 0,
    userCities: [],
    loader: false,
    tabbar: {
      "backgroundColor": "#ffffff",
      "color": "#999999",
      "selectedColor": "#999999",
      "borderStyle": "white",
      list: [{
          "pagePath": "/pages/index/index",
          "text": "首 页",
          "iconPath": "/images/tabbar/tabbar1.png",
          "selectedIconPath": "/images/tabbar/tabbar1a.png"
        },
        {
          "pagePath": "/pages/test/index/index",
          "text": "职业测评",
          "iconPath": "/images/tabbar/tabbar2.png",
          "selectedIconPath": "/images/tabbar/tabbar2a.png"
        },
        {
          "pagePath": "/pages/volunteer/index/index",
          "text": "AI填报志愿",
          "iconPath": "/images/tabbar/scan.png",
          "scan": true,
          "selectedIconPath": "/images/tabbar/scan.png"
        },
        {
          "pagePath": "/pages/guide/index",
          "text": "志愿指导",
          "iconPath": "/images/tabbar/tabbar3.png",
          "selectedIconPath": "/images/tabbar/tabbar3a.png"
        },
        {
          "pagePath": "/pages/my/index",
          "text": "我 的",
          "type": 'my',
          "iconPath": "/images/tabbar/tabbar4.png",
          "selectedIconPath": "/images/tabbar/tabbar4a.png"
        }
      ]
    },
    tabbarHeight: 134,

  },
  testLocation() {
    var item = {
      "code": 350000,
      "parentCode": 0,
      "level": "L1",
      "children": [],
      "name": "福建",
      "id": 1141,
      "leaf": true
    }
    wx.setStorageSync('userCitys', item)
    wx.hideLoading({});
  }
})
